package SecurityMessage;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @创建人 MBY381
 * @创建时间 2022/6/1 09:16
 * @描述 暂无
 */
public class MACUtils {
    private static final int MAC_KEY_LENGTH = 32;

    public static byte[] mac(String algorithm, Key key, byte[] data) throws Exception {
        Mac mac = Mac.getInstance(algorithm);
        mac.init(key);
        return mac.doFinal(data);
    }

    public  static String generateKey() throws NoSuchAlgorithmException {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < MAC_KEY_LENGTH; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();

//        KeyGenerator keyGen = KeyGenerator.getInstance(MAC_ALGORITHM);
//        SecretKey secretKey = keyGen.generateKey();
//        return new SecretKeySpec(secretKey.getEncoded(), MAC_ALGORITHM).toString();
    }

    public static String bytesToString(byte[] encryptByte) {
        String result = "";
        for (Byte bytes : encryptByte) {
            result += bytes.toString() + " ";
        }
        return result;
    }

    public static byte[] stringToBytes(String data) {
        String[] strArr = data.split(" ");
        int len = strArr.length;
        byte[] clone = new byte[len];
        for (int i = 0; i < len; i++) {
            clone[i] = Byte.parseByte(strArr[i]);
        }

        return clone;
    }

    public static void main(String[] args) throws Exception {
        byte[] bytes = "二五人被我让你弄哦ii".getBytes(StandardCharsets.UTF_8);
        Key key = new SecretKeySpec("266f5fe18e714688a083df4ca9f78064".getBytes(), "");
        byte[] data=mac("HmacMD5",key,bytes);
        System.out.println(data);
        System.out.println(new String(data));
    }
}
